package com.whfc.safety.xxl.job;

import com.alibaba.fastjson.JSONObject;
import com.whfc.XxlJobConfig;
import com.whfc.common.util.DateUtil;
import com.whfc.safety.dao.SafetyCheckMapper;
import com.whfc.safety.dao.SafetyCheckStatisticsDayMapper;
import com.whfc.safety.dao.SafetyDangerMapper;
import com.whfc.safety.entity.SafetyCheckStatisticsDay;
import com.whfc.safety.param.SafetyCheckParam;
import com.whfc.safety.param.SafetyCheckUserParam;
import com.whfc.safety.service.SafetyCheckService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description 安全问题定时任务
 * @Author hw
 * @Date 2021-08-31 10:03
 * @Version 1.0
 */
@Component
@ConditionalOnBean(XxlJobConfig.class)
public class SafetyCheckJob {


    @Autowired
    private SafetyCheckMapper safetyCheckMapper;

    @Autowired
    private SafetyDangerMapper safetyDangerMapper;

    @Autowired
    private SafetyCheckService safetyCheckService;

    @Autowired
    private SafetyCheckStatisticsDayMapper safetyCheckStatisticsDayMapper;


    @XxlJob("safetyCheckUpdateOverdue")
    public void safetyCheckUpdateOverdue() {
        try {
            List<Integer> checkIds = safetyCheckMapper.selectCheckIdAll();
            XxlJobHelper.log("开始执行更新安全问题超期任务,超期任务ID{}", checkIds);
            if (checkIds != null && !checkIds.isEmpty()) {
                safetyCheckMapper.updateOverdue(checkIds);
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行更新安全问题超期任务失败{}" + e.getMessage());
        }
    }

    @XxlJob("safetyDangerUpdateOverdue")
    public void safetyDangerUpdateOverdue() {
        try {
            List<Integer> checkIds = safetyDangerMapper.selectDangerIdAll();
            XxlJobHelper.log("开始执行更新安全问题超期任务,超期任务ID{}", checkIds);
            if (checkIds != null && !checkIds.isEmpty()) {
                safetyDangerMapper.updateOverdue(checkIds);
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行更新安全问题超期任务失败{}" + e.getMessage());
        }
    }

    @XxlJob("safetyGenerateData")
    protected void safetyGenerateData() {
        try {
            XxlJobHelper.log("执行安全演示数据生成");
            String str1 = "{\"deptId\":16,\"partId\":18,\"partName\":\"\\t\\r\\n地基与基础工程/\\t\\r\\n基础工程\\t\\r\\n基础混凝土浇筑\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"安全管理\",\"issueId\":\"737982434804498432\",\"issueContent\":\"砌筑过程中墙体失稳、倾倒\",\"rectifyRequire\":\"边坡顶部承载力过重，边坡锚杆深度不够或预应力张力不到位，孔内水泥灌浆不饱满、边坡监测不到位等造成的边坡塌陷。\",\"rectifyDuration\":\""+ cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":2,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917185031239.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"乐洋\",\"userPhone\":\"17363303334\",\"userId\":31},{\"type\":3,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str2 = "{\"deptId\":16,\"partId\":13,\"partName\":\"\\t\\r\\n地基与基础工程/\\t\\r\\n地基开挖支护\\t\\r\\n基坑支护\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"安全管理\",\"issueId\":\"737988734531665920\",\"issueContent\":\"喷浆不均匀，脱色，掉粉等\",\"rectifyRequire\":\"喷浆均匀，不脱色，不掉粉\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"该工程不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917201643295.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"王钢\",\"userPhone\":\"17612182237\",\"userId\":35},{\"type\":3,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str3 = "{\"deptId\":16,\"partId\":13,\"partName\":\"\\t\\r\\n地基与基础工程/\\t\\r\\n地基开挖支护\\t\\r\\n基坑支护\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"安全管理\",\"issueId\":\"737992570772127744\",\"issueContent\":\"砼浇筑局部存在质量缺陷\",\"rectifyRequire\":\"按照规范要求整改\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917220564240.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33},{\"type\":3,\"userName\":\"潘玉良\",\"userPhone\":\"13886199362\",\"userId\":42},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"方戴佳美\",\"userPhone\":\"18971400342\",\"userId\":32}]}";
            String str4 = "{\"deptId\":16,\"partId\":12,\"partName\":\"\\t\\r\\n地基与基础工程/\\t\\r\\n地基开挖支护\\t\\r\\n基槽开挖\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"安全管理\",\"issueId\":\"737993013820653568\",\"issueContent\":\"墙体不平整\",\"rectifyRequire\":\"进行修补\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917241262081.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"袁帅\",\"userPhone\":\"19526000610\",\"userId\":34},{\"type\":3,\"userName\":\"柯祖良\",\"userPhone\":\"15072013434\",\"userId\":38},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"方戴佳美\",\"userPhone\":\"18971400342\",\"userId\":32}]}";
            String str5 = "{\"deptId\":16,\"partId\":11,\"partName\":\"\\t\\r\\n地基与基础工程\\t\\r\\n地基开挖支护\",\"issueTypeId\":\"737965998958706688\",\"issueTypeName\":\"安全管理\",\"issueId\":\"737992421136138240\",\"issueContent\":\"砖墙接槎或预留脚手眼不符合规范要求\",\"rectifyRequire\":\"砖墙接槎或预留脚手眼得符合规范要求\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":2,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917285280782.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33},{\"type\":3,\"userName\":\"柯祖良\",\"userPhone\":\"15072013434\",\"userId\":38},{\"type\":4,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":5,\"userName\":\"李华\",\"userPhone\":\"13971675821\",\"userId\":33}]}";
            String str6 = "{\"deptId\":16,\"partId\":7,\"partName\":\"防水工程\",\"issueTypeId\":\"750758286239727616\",\"issueTypeName\":\"质量管理\",\"issueId\":\"750758286239727616\",\"issueContent\":\"不安全\",\"rectifyRequire\":\"防水做到位\",\"rectifyDuration\":\""+cn.hutool.core.date.DateUtil.tomorrow()+"\",\"urgency\":1,\"checkDesc\":\"不合格\",\"address\":\"陕西省西安市新城区解放门街道宝康宾馆宝康大厦\",\"lng\":108.961622,\"lat\":34.273867,\"imgUrls\":[\"https://files.anculsai.com/ms/pro/safety/img/2022080917304259147.png\"],\"checkUsers\":[{\"type\":2,\"userName\":\"安妮大胖纸\uD83D\uDD1D\",\"userPhone\":\"18772378012\",\"userId\":26},{\"type\":3,\"userName\":\"胡俊\",\"userPhone\":\"18672766222\",\"userId\":30},{\"type\":4,\"userName\":\"袁帅\",\"userPhone\":\"19526000610\",\"userId\":34},{\"type\":5,\"userName\":\"方戴佳美\",\"userPhone\":\"18971400342\",\"userId\":32}]}";

            List<String> strs = Arrays.asList(str1,str2,str3,str4,str5,str6);
            strs.forEach(s -> {
                SafetyCheckParam checkParam = JSONObject.parseObject(s,SafetyCheckParam.class);
                SafetyCheckUserParam userParam = new SafetyCheckUserParam();
                userParam.setType(1);
                userParam.setUserId(41);
                userParam.setUserName("冯和任");
                userParam.setUserPhone("13886199362");
                checkParam.getCheckUsers().add(userParam);
                List<SafetyCheckUserParam> safetyCheckUserParams = checkParam.getCheckUsers().stream().filter(Objects::nonNull).collect(Collectors.toList());
                Collections.sort(safetyCheckUserParams);
                checkParam.setCheckUsers(safetyCheckUserParams);
                checkParam.setCheckUserId(41);
                checkParam.setCheckUserName("冯和任");
                XxlJobHelper.log(s);
                safetyCheckService.addCheck(checkParam);
            });

        } catch (Exception e) {
            XxlJobHelper.handleFail("执行安全演示数据生成的任务失败.error:" + e);
        }
    }

    @XxlJob("safetyCheckStatisticsDay")
    protected void safetyCheckStatisticsDay() {
        try {
            XxlJobHelper.log("执行安全每天统计的任务");
            //获取时间 统计昨天的安全检查
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date yesterday = calendar.getTime();

            List<SafetyCheckStatisticsDay> statisticsDayList = new ArrayList<>();

            //取出需要定时统计的组织机构
            List<Integer> list = safetyCheckMapper.selectSafetyDeptIds();
            for (Integer deptId : list) {
                SafetyCheckStatisticsDay statisticsDay = new SafetyCheckStatisticsDay();
                statisticsDay.setDeptId(deptId);
                statisticsDay.setDate(yesterday);
                // 昨天新增
                Integer newIssueNum = safetyCheckMapper.countCheckNewIssue(deptId, DateUtil.getDateBegin(yesterday), DateUtil.getDateEnd(yesterday));
                statisticsDay.setNewIssueNum(newIssueNum);
                // 昨天待整改
                Integer todoIssueNum = safetyCheckMapper.countCheckToBeRectified(deptId);
                statisticsDay.setTodoIssueNum(todoIssueNum);
                // 昨天完成
                Integer completeIssueNum = safetyCheckMapper.countCheckComplete(deptId, yesterday);
                statisticsDay.setCompleteIssueNum(completeIssueNum);
                statisticsDayList.add(statisticsDay);
            }
            //保存记录
            safetyCheckStatisticsDayMapper.batchInsert(statisticsDayList);
        } catch (Exception e) {
            XxlJobHelper.handleFail("执行安全每天统计的任务失败.error:" + e);
        }
    }
}
